﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;
using System.IO;


namespace MarginTrading.Forms
{
    public partial class SettlementsWnd : Form
    {
        double fBuyTotal = 0;
        double fSellTotal = 0;
        bool bTableDrawn = false;

        string sCurrentAgentCode = "";
        string sCurrentBrokerCode = "";
        DateTime currentDate;

        public SettlementsWnd()
        {
            InitializeComponent();
        }

        private void SettlementsWnd_Load(object sender, EventArgs e)
        {
            try
            {
	            Config config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_DEPLOYMENT_SIDE);
	
	            if (config.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_BROKER)
	            {
	                AgentCollection agentCollection = AgentServices.GetAgentCollection();
	
	                for (int iI = 0; iI < agentCollection.Count; iI++)
	                {
	                    comboBoxAgentCode.Items.Add(agentCollection[iI].Code);
	                }
	
	                config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_COMPANY_CODE);
	                comboBoxBrokerCode.Items.Add(config.Value);
	                comboBoxBrokerCode.SelectedIndex = 0;
	                comboBoxAgentCode.SelectedIndex = 0;
	
	                labelSellTotal.Text = "0";
	                labelBuyTotal.Text = "0";
	            }
	            else if (config.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_AGENT)
	            {
	                BrokerCollection brokerCollection = BrokerServices.GetBrokerCollection();
	
	                for (int iI = 0; iI < brokerCollection.Count; iI++)
	                {
	                    comboBoxBrokerCode.Items.Add(brokerCollection[iI].Code);
	                }
	
	                config = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_COMPANY_CODE);
	                comboBoxAgentCode.Items.Add(config.Value);
	                comboBoxAgentCode.SelectedIndex = 0;
	                comboBoxBrokerCode.SelectedIndex = 0;
	            }
            }
            catch (System.Exception ex)
            {
            	
            }

            //dataGridViewBuy.Width = (Size.Width - 60) / 2;
            //dataGridViewBuy.Height = Size.Height - 140;

            //dataGridViewSell.Left = (Width - 10) / 2;
            //dataGridViewSell.Width = (Size.Width - 60) / 2;
            //dataGridViewSell.Height = Size.Height - 140;

            WindowState = FormWindowState.Maximized;
        }

        private void SettlementsWnd_SizeChanged(object sender, EventArgs e)
        {
            dataGridViewBuy.Width = (Size.Width - 75) / 2;
            dataGridViewBuy.Height = Size.Height - 170;
            dataGridViewBuy.Left = 20;

            dataGridViewSell.Width = (Size.Width - 75) / 2;
            dataGridViewSell.Height = Size.Height - 170;
            dataGridViewSell.Left = dataGridViewSell.Width + 40;

            //MessageBox.Show(" " + dataGridViewBuy.Left + " " + dataGridViewBuy.Right + " " + dataGridViewSell.Left + " " + dataGridViewSell.Right + " " + Width);

            int iClearance = 80;
            labelSellTotal.Top = Height - iClearance;
            labelBuyTotal.Top = Height - iClearance;
            labelTotal1.Top = Height - iClearance;
            labelTotal2.Top = Height - iClearance;
            buttonSellSettle.Top = Height - iClearance - 2;
            buttonBuySettle.Top = Height - iClearance - 2;
            labelSellTotal.Left = dataGridViewSell.Left + 60;
            labelTotal2.Left = dataGridViewSell.Left;
            buttonSellSettle.Left = dataGridViewSell.Left + 160;
            labelBuyTotal.Left = dataGridViewBuy.Left + 60;
            labelTotal1.Left = dataGridViewBuy.Left;
            buttonBuySettle.Left = dataGridViewBuy.Left + 160;
            labelBuySide.Top = dataGridViewBuy.Top - 20;
            labelSellSide.Top = dataGridViewSell.Top - 20;
            labelBuySide.Left = dataGridViewBuy.Left + ((dataGridViewBuy.Width - labelBuySide.Width) / 2);
            labelSellSide.Left = dataGridViewSell.Left + ((dataGridViewSell.Width - labelSellSide.Width) / 2);
            buttonLoadSelBuy.Left = dataGridViewBuy.Left;
            buttonLoadSelSell.Left = dataGridViewSell.Left;

            if (bTableDrawn)
            {
                dataGridViewSell.Columns[0].Width = 50;
                dataGridViewSell.Columns[1].Width = 150;

                dataGridViewSell.Columns[4].Width = dataGridViewSell.Width -
                    (200
                    + dataGridViewSell.Columns[2].Width
                    + dataGridViewSell.Columns[3].Width
                    + 2);

                dataGridViewBuy.Columns[0].Width = 50;
                dataGridViewBuy.Columns[1].Width = 150;

                dataGridViewBuy.Columns[4].Width = dataGridViewBuy.Width -
                (200
                + dataGridViewBuy.Columns[2].Width
                + dataGridViewBuy.Columns[3].Width
                + 2);
            }
        }

        private void buttonGO_Click(object sender, EventArgs e)
        {
            int iCount = dataGridViewSell.Columns.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                dataGridViewSell.Columns.RemoveAt(0);
            }

            iCount = dataGridViewBuy.Columns.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                dataGridViewBuy.Columns.RemoveAt(0);
            }

            DataGridViewCheckBoxColumn Chk1 = new DataGridViewCheckBoxColumn();
            Chk1.HeaderText = "Select";
            Chk1.Frozen = true;
            Chk1.Name = "Chk1";
            dataGridViewBuy.Columns.Add(Chk1);
            dataGridViewBuy.Columns["Chk1"].DisplayIndex = 0;

            DataGridViewCheckBoxColumn Chk2 = new DataGridViewCheckBoxColumn();
            Chk2.HeaderText = "Select";
            Chk2.Name = "Chk2";
            dataGridViewSell.Columns.Add(Chk2);
            dataGridViewSell.Columns["Chk2"].DisplayIndex = 0;

            sCurrentAgentCode = comboBoxAgentCode.Text;
            sCurrentBrokerCode = comboBoxBrokerCode.Text;
            currentDate = dateTimePicker.Value;

            try
            {
                dataGridViewBuy.DataSource = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value,
                    comboBoxBrokerCode.Text, comboBoxAgentCode.Text, "B");

                dataGridViewSell.DataSource = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value,
                    comboBoxBrokerCode.Text, comboBoxAgentCode.Text, "S");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Failed to fetch settlement data table. Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            for (int iI = 0; iI < dataGridViewBuy.Columns.Count; iI++)
            {
                dataGridViewBuy.Columns[iI].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            for (int iI = 0; iI < dataGridViewSell.Columns.Count; iI++)
            {
                dataGridViewSell.Columns[iI].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            dataGridViewBuy.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
            dataGridViewSell.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;

            bTableDrawn = true;

            fBuyTotal = 0;
            fSellTotal = 0;
            labelSellTotal.Text = "0.00";
            labelBuyTotal.Text = "0.00";

            Config c = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_DEPLOYMENT_SIDE);

            if (c.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_AGENT)
            {
                for (int iI = 0; iI < dataGridViewBuy.Rows.Count; iI++)
                {
                    dataGridViewBuy.Rows[iI].Cells[0].Value = true;
                    fBuyTotal += double.Parse(dataGridViewBuy.Rows[iI].Cells[4].Value.ToString());
                    labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal); //fBuyTotal.ToString();
                }
            }
            else
            {
                for (int iI = 0; iI < dataGridViewSell.Rows.Count; iI++)
                {
                    dataGridViewSell.Rows[iI].Cells[0].Value = true;
                    fSellTotal += double.Parse(dataGridViewSell.Rows[iI].Cells[4].Value.ToString());
                    labelSellTotal.Text = String.Format("{0:0.00}", fSellTotal);
                }
            }

            SettlementsWnd_SizeChanged(null, null);
        }

        private void dataGridViewBuy_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewBuy.CurrentCell.ColumnIndex != 0)
            {
                return;
            }

            Config c = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_DEPLOYMENT_SIDE);

            if (c.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_BROKER)
            {
                return;
            }

            if (dataGridViewBuy.CurrentCell.Value == null
                || (bool)dataGridViewBuy.CurrentCell.Value == false)
            {
                dataGridViewBuy.CurrentCell.Value = true;
                fBuyTotal += double.Parse(dataGridViewBuy.CurrentRow.Cells[4].Value.ToString());
                labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal); //fBuyTotal.ToString();
            }
            else
            {
                dataGridViewBuy.CurrentCell.Value = false;
                fBuyTotal -= double.Parse(dataGridViewBuy.CurrentRow.Cells[4].Value.ToString());
                labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal); //fBuyTotal.ToString();
            }
        }

        private void dataGridViewSell_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewSell.CurrentCell.ColumnIndex != 0)
            {
                return;
            }

            Config c = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_DEPLOYMENT_SIDE);

            if (c.Value == Constants.CONFIG_VALUE_DEPLOYMENT_SIDE_AGENT)
            {
                return;
            }

            if (dataGridViewSell.CurrentCell.Value == null
                || (bool)dataGridViewSell.CurrentCell.Value == false)
            {
                dataGridViewSell.CurrentCell.Value = true;
                double value = double.Parse(dataGridViewSell.CurrentRow.Cells[4].Value.ToString());
                fSellTotal = value + fSellTotal;
                labelSellTotal.Text = String.Format("{0:0.00}", fSellTotal);
            }
            else
            {
                dataGridViewSell.CurrentCell.Value = false;
                fSellTotal -= double.Parse(dataGridViewSell.CurrentRow.Cells[4].Value.ToString());
                labelSellTotal.Text = String.Format("{0:0.00}", fSellTotal);
            }
        }

        private void buttonBuySettle_Click(object sender, EventArgs e)
        {
            if (fBuyTotal == 0)
            {
                MessageBox.Show("No entries selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            DialogResult result = MessageBox.Show("You are going to settle Rs. " + fBuyTotal + Environment.NewLine + "Press OK to proceed", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (result != DialogResult.OK)
            {
                return;
            }

            StringBuilder clientIDs = new StringBuilder();
            string sFileName = sCurrentBrokerCode + "," + sCurrentAgentCode + ",BUY," + currentDate.ToLongDateString();
            //clientIDs.AppendLine(sFileName);
            bool bFailed = false;
            string sError = "";
            bool bSettled = false;
            int iCount = dataGridViewBuy.Rows.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                if (dataGridViewBuy.Rows[iI].Cells[0].Value != null &&
                    (bool)dataGridViewBuy.Rows[iI].Cells[0].Value == true)
                {
                    string clientCode = dataGridViewBuy.Rows[iI].Cells[1].Value.ToString();
                    try
                    {
                        string sReferenceNO = GetReferenceCode("PA");
                        DailyTransactionsServices.Settle(clientCode, currentDate, sCurrentBrokerCode, "B", sReferenceNO);
                        LoanAccount accountEntry = new LoanAccount();

                        accountEntry.Amount = double.Parse(dataGridViewBuy.Rows[iI].Cells[4].Value.ToString());
                        accountEntry.ReferenceNo = sReferenceNO;
                        accountEntry.ClientCode = clientCode;
                        accountEntry.CreatedDate = DateTime.Today;
                        accountEntry.EntryType = "PA";
                        accountEntry.TrParticulars = "Payment on Purchases"; //Ravin1
                        accountEntry.Remarks = "Payment on Purchases"; //Ravin1

                        LoanAccountServices.Add(accountEntry);

                        bSettled = true;

                        string sLine = string.Format("{0,-15}{1,-8}{2,-12}{3,-20}", clientCode.Substring(4),
                            DateTime.Today.ToString("ddMMyyyy"), String.Format("{0:0.00}", accountEntry.Amount),
                            "                    ");

                        //string sLine = clientCode.Substring(4);

                        //sLine += DateTime.Today.ToString("ddMMyyyy");
                        //string sAmmount = "            ";

                        //sAmmount = sAmmount.Substring(String.Format("{0:0.00}", accountEntry.Amount).Length) +
                        //    String.Format("{0:0.00}", accountEntry.Amount);

                        //sLine += sAmmount;
                        //sLine += "          ";  //for bank code
                        sLine += "0";    //for non initial settlements (1 for initial settlements)

                        clientIDs.AppendLine(sLine);
                    }
                    catch (System.Exception ex)
                    {
                        bFailed = true;
                        sError += ex.Message;
                    }
                    finally
                    {
                        dataGridViewBuy.Rows[iI].Cells[0].Value = false;
                        fBuyTotal -= double.Parse(dataGridViewBuy.Rows[iI].Cells[4].Value.ToString());
                        labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal);
                    }
                }
            }

            if (bFailed)
            {
                MessageBox.Show("Updating database failed. Error: " + sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (bSettled)
            {
                MessageBox.Show("Settling successful");

                InitialSettlementCollection collection = InitialSettlementServices.GetToBeSentInitialSettlementCollection(sCurrentBrokerCode, sCurrentAgentCode);

                for (int iI = 0; iI < collection.Count; iI++)
                {
                    InitialSettlement sett = collection[iI];

                    string sLine = string.Format("{0,-15}{1,-8}{2,-12}{3,-20}", sett.ClientCode.Substring(4),
                            sett.UpdatedDate.ToString("ddMMyyyy"), String.Format("{0:0.00}", sett.SettledAmount),
                            "                    ");

                    //string sLine = sett.ClientCode.Substring(4);

                    //sLine += sett.UpdatedDate.ToString("ddMMyyyy");
                    //string sAmmount = "            ";

                    //sAmmount = sAmmount.Substring(String.Format("{0:0.00}", sett.SettledAmount).Length) +
                    //    String.Format("{0:0.00}", sett.SettledAmount);

                    //sLine += sAmmount;
                    //sLine += "          ";  //for bank code
                    sLine += "1";

                    clientIDs.AppendLine(sLine);
                }

                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MarginTrading");
                Directory.CreateDirectory(path);
                path = Path.Combine(path, sFileName);

                bool bWritten = false;
                using (StreamWriter outfile = new StreamWriter(path))
                {
                    try
                    {
                        outfile.Write(clientIDs.ToString());
                        bWritten = true;
                    }
                    catch (System.Exception ex)
                    {
                    }
                }
                if (bWritten == true)
                {
                    InitialSettlementServices.MarkSentInitialSettlementCollection(sCurrentBrokerCode, sCurrentAgentCode);
                }
                
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Selection Files|*.sel";
                saveFileDialog1.Title = "Save Settled Selection";
                saveFileDialog1.FileName = sFileName;
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    using (StreamWriter outfile = new StreamWriter(saveFileDialog1.FileName))
                    {
                        outfile.Write(clientIDs.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("No entries selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ResetTables();

            BuySettlementSummary buySettlementSummary = new BuySettlementSummary(comboBoxAgentCode.Text, dateTimePicker.Value);
            buySettlementSummary.Show();
        }

        private void buttonSellSettle_Click(object sender, EventArgs e)
        {
            if (fSellTotal == 0)
            {
                MessageBox.Show("No entries selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            DialogResult result = MessageBox.Show("You are going to settle Rs. " + fSellTotal + Environment.NewLine + "Press OK to proceed", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (result != DialogResult.OK)
            {
                return;
            }

            StringBuilder clientIDs = new StringBuilder();
            string sFileName = sCurrentBrokerCode + "," + sCurrentAgentCode + ",SELL," + currentDate.ToLongDateString();
            //clientIDs.AppendLine(sFileName);
            int iCount = dataGridViewSell.Rows.Count;
            bool bFailed = false;
            string sError = "";
            bool bSettled = false;
            for (int iI = 0; iI < iCount; iI++)
            {
                if (dataGridViewSell.Rows[iI].Cells[0].Value != null &&
                    (bool)dataGridViewSell.Rows[iI].Cells[0].Value == true)
                {
                    string clientCode = dataGridViewSell.Rows[iI].Cells[1].Value.ToString();
                    LoanAccount accountEntry = new LoanAccount();
                    try
                    {
                        string sReferenceNO = GetReferenceCode("RC");
                        DailyTransactionsServices.Settle(clientCode, currentDate, sCurrentBrokerCode, "S", sReferenceNO);
                        accountEntry.Amount = double.Parse(dataGridViewSell.Rows[iI].Cells[4].Value.ToString());
                        accountEntry.ReferenceNo = sReferenceNO;
                        accountEntry.ClientCode = clientCode;
                        accountEntry.CreatedDate = DateTime.Today;
                        accountEntry.EntryType = "RC";
                        accountEntry.TrParticulars = "Receipt on Sales"; //Ravin1
                        accountEntry.Remarks = "Receipt on Sales"; //Ravin1

                        accountEntry.Amount *= -1;

                        LoanAccountServices.Add(accountEntry);
                        bSettled = true;

                        string sLine = string.Format("{0,-15}{1,-8}{2,-12}{3,-20}", clientCode.Substring(4),
                            DateTime.Today.ToString("ddMMyyyy"), String.Format("{0:0.00}", accountEntry.Amount),
                            "                    ");

                        //sLine += DateTime.Today.ToString("ddMMyyyy");
                        //string sAmmount = "            ";

                        //sAmmount = sAmmount.Substring(String.Format("{0:0.00}", accountEntry.Amount).Length) +
                        //    String.Format("{0:0.00}", accountEntry.Amount);

                        //sLine += sAmmount;
                        //sLine += "          ";  //for bank code
                        sLine += "0";

                        clientIDs.AppendLine(sLine);
                    }
                    catch (System.Exception ex)
                    {
                        bFailed = true;
                        sError += ex.Message;
                    }
                    finally
                    {
                        dataGridViewSell.Rows[iI].Cells[0].Value = false;
                        fSellTotal -= double.Parse(dataGridViewSell.Rows[iI].Cells[4].Value.ToString());
                        labelSellTotal.Text = String.Format("{0:0.00}", fSellTotal);
                    }
                }
            }
            if (bFailed)
            {
                MessageBox.Show("Updating database failed. Error: " + sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (bSettled)
            {
                MessageBox.Show("Settling successful");

                InitialSettlementCollection collection = InitialSettlementServices.GetToBeSentInitialSettlementCollection(sCurrentBrokerCode, sCurrentAgentCode);

                for (int iI = 0; iI < collection.Count; iI++)
                {
                    InitialSettlement sett = collection[iI];

                    string sLine = string.Format("{0,-15}{1,-8}{2,-12}{3,-20}", sett.ClientCode.Substring(4),
                            sett.UpdatedDate.ToString("ddMMyyyy"), String.Format("{0:0.00}", sett.SettledAmount),
                            "                    ");

                    //string sLine = sett.ClientCode.Substring(4);

                    //sLine += sett.UpdatedDate.ToString("ddMMyyyy");
                    //string sAmmount = "            ";

                    //sAmmount = sAmmount.Substring(String.Format("{0:0.00}", sett.SettledAmount).Length) +
                    //    String.Format("{0:0.00}", sett.SettledAmount);

                    //sLine += sAmmount;
                    //sLine += "          ";  //for bank code
                    sLine += "1";

                    clientIDs.AppendLine(sLine);
                }

                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MarginTrading");
                Directory.CreateDirectory(path);
                path = Path.Combine(path, sFileName);

                bool bWritten = false;
                using (StreamWriter outfile = new StreamWriter(path))
                {
                    try
                    {
                        outfile.Write(clientIDs.ToString());
                        bWritten = true;
                    }
                    catch (System.Exception ex)
                    {
                    }
                }
                if (bWritten == true)
                {
                    InitialSettlementServices.MarkSentInitialSettlementCollection(sCurrentBrokerCode, sCurrentAgentCode);
                }

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Selection Files|*.sel";
                saveFileDialog1.Title = "Save Settled Selection";
                saveFileDialog1.FileName = sFileName;
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    using (StreamWriter outfile = new StreamWriter(saveFileDialog1.FileName))
                    {
                        outfile.Write(clientIDs.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("No entries selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ResetTables();

            SellSettlementSummary sellSettlementSummary = new SellSettlementSummary(comboBoxAgentCode.Text, dateTimePicker.Value);
            sellSettlementSummary.Show();
        }

        private void ResetTables()
        {
            comboBoxBrokerCode.Text = sCurrentBrokerCode;
            comboBoxAgentCode.Text = sCurrentAgentCode;
            dateTimePicker.Value = currentDate;
            buttonGO_Click(null, null);
        }

        private string GetReferenceCode(string sType)
        {
            return sType + "-" + Program.GetNextSeqNO().ToString();
        }

        private void buttonLoadSelBuy_Click(object sender, EventArgs e)
        {
            OnLoadSelFile("BUY", dataGridViewBuy);
        }

        private void buttonLoadSelSell_Click(object sender, EventArgs e)
        {
            OnLoadSelFile("SELL", dataGridViewSell);
        }

        private void OnLoadSelFile(string sSide, DataGridView dataGridView)
        {
            for (int iI = 0; iI < dataGridView.Rows.Count; iI++)
            {
                dataGridView.Rows[iI].Cells[0].Value = false;
            }
            if (sSide == "BUY")
            {
                fBuyTotal = 0;
                labelBuyTotal.Text = "0";
            }
            else
            {
                fSellTotal = 0;
                labelSellTotal.Text = "0";
            }

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Selection Files|*.sel";
            openFileDialog1.Title = "Select selection file";
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
                {
                    String line;
                    //line = sr.ReadLine();
                    //if (line == null)
                    //{
                    //    return;
                    //}

                    //string[] tokens = line.Split(',');
                    //if (tokens.Length != 6)
                    //{
                    //    MessageBox.Show("Invalid selection file" , "Error", MessageBoxButtons.OK,
                    //        MessageBoxIcon.Asterisk);

                    //    return;
                    //}
                    //if (tokens[0] != sCurrentBrokerCode)
                    //{
                    //    MessageBox.Show("Selection file does not match the current query criteria" 
                    //        + Environment.NewLine + "Invalid Broker", "Error", MessageBoxButtons.OK, 
                    //        MessageBoxIcon.Asterisk);

                    //    return;
                    //}

                    //if (tokens[1] != sCurrentAgentCode)
                    //{
                    //    MessageBox.Show("Selection file does not match the current query criteria"
                    //        + Environment.NewLine + "Invalid Agent", "Error", MessageBoxButtons.OK,
                    //        MessageBoxIcon.Asterisk);

                    //    return;
                    //}

                    //if (tokens[2] != sSide)
                    //{
                    //    MessageBox.Show("Selection file does not match the current query criteria"
                    //        + Environment.NewLine + "Invalid Side", "Error", MessageBoxButtons.OK,
                    //        MessageBoxIcon.Asterisk);

                    //    return;
                    //}

                    //string sDate = tokens[3] + "," + tokens[4] + "," + tokens[5];
                    //if (sDate != currentDate.ToLongDateString())
                    //{
                    //    MessageBox.Show("Selection file does not match the current query criteria"
                    //        + Environment.NewLine + "Invalid Date", "Error", MessageBoxButtons.OK,
                    //        MessageBoxIcon.Asterisk);

                    //    return;
                    //}

                    while ((line = sr.ReadLine()) != null)
                    {
                        string sClientCode = sCurrentBrokerCode + "-" + line.Substring(0, 15);
                        char[] trimchar = {' '};
                        sClientCode = sClientCode.TrimEnd(trimchar);
                        string sInitial = line.Substring(line.Length - 1);
                        if (sInitial == "1")
                        {
                            continue;
                        }

                        double dFileAmount = double.Parse(line.Substring(23, 12));
                        if (dFileAmount < 0)
                        {
                            dFileAmount *= -1;
                        }

                        int iCount = dataGridView.Rows.Count;
                        for (int iI = 0; iI < iCount; iI++)
                        {
                            string clientCode = dataGridView.Rows[iI].Cells[1].Value.ToString();
                            if (clientCode == sClientCode)
                            {
                                dataGridView.Rows[iI].Cells[0].Value = true;
                                double dTableAmount = double.Parse(dataGridView.Rows[iI].Cells[4].Value.ToString());
                                if (dTableAmount != dFileAmount)
                                {
                                    MessageBox.Show("Amount conflict!" + Environment.NewLine + Environment.NewLine +
                                    "Possible causes:" + Environment.NewLine + 
                                    "1. Selection file may not match the current query criteria" + Environment.NewLine +
                                    "2. Selection file is corrupted or modified", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    for (int iJ = 0; iJ < dataGridView.Rows.Count; iJ++)
                                    {
                                        dataGridView.Rows[iJ].Cells[0].Value = false;
                                    }
                                    return;
                                }

                                if (sSide == "BUY")
                                {
                                    fBuyTotal += dTableAmount;
                                    labelBuyTotal.Text = fBuyTotal.ToString();
                                }
                                else
                                {
                                    fSellTotal += dTableAmount;
                                    labelSellTotal.Text = fBuyTotal.ToString();
                                }
                                
                            }
                        }
                    }
                }
            }
        }
    }
}
